//
//  GHLoginViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/14.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "THLoginHomeViewController.h"
#import "THRegisterViewController.h"
#import "THRegisterViewController.h"
#import "THForgotPwdViewController.h"
#import "THCodeLoginViewController.h"
@interface THLoginHomeViewController ()
@property(nonatomic, strong) UITextField                     *accountTextFiled;
@property(nonatomic, strong) UITextField                     *pwdTextFiled;

@end
@implementation THLoginHomeViewController
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    [self stoneobs_fun_st_autoAdjustAllResponder];
    [self configSubView];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)onSelctedRegister{
    __weak typeof(self) weakSelf =  self;
    STTools_ActionSheet * sheet = [STTools_ActionSheet stoneobs_fun_actionSheetWithTitle:@"请选择身份" buttonTitles:@[@"普通注册",@"小店",@"企业"] cancelTitle:@"取消" handle:^(NSInteger index) {
        
        
        THRegisterViewController * vc= THRegisterViewController.new;
        vc.type = index ;
        [weakSelf pushViewController:vc animated:1];
        
    }];
    [sheet show];
}
#pragma mark --subView
- (void)configSubView{
     __weak typeof(self) weakSelf =  self;
    self.navigationController.navigationBar.hidden = YES;
    self.cus_navgationBar.backgroundColor = UIColor.whiteColor;
    [self.cus_navgationBar.rightButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.cus_navgationBar.titleButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.cus_navgationBar.rightButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedRegister];
    }];
    self.cus_navgationBar.leftButton.hidden = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    self.tableView.backgroundColor = UIColor.whiteColor;


    
    UIView * header = [[UIView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 80, 80)];
    imageView.image = [UIImage imageNamed:@"logo"];
    imageView.layer.cornerRadius = 8;
    imageView.clipsToBounds = YES;
    imageView.centerX = UISCREEN_WIDTH / 2;
    imageView.backgroundColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    [header addSubview:imageView];
    

    
    self.accountTextFiled = [self textFiledWithLeftImage:@"手机号" placeHolader:@"请输入手机号码"];
    self.accountTextFiled.top = imageView.bottom +40 ;
    [header addSubview:self.accountTextFiled];

    
    self.pwdTextFiled = [self textFiledWithLeftImage:@"请输入密码" placeHolader:@"请输入密码"];
    self.pwdTextFiled.top = self.accountTextFiled.bottom+24 ;
    self.pwdTextFiled.secureTextEntry = YES;
    [header addSubview:self.pwdTextFiled];
    

    

    
    
    STButton * button = [[STButton alloc] initWithFrame:CGRectMake(40, self.pwdTextFiled.bottom + 80, UISCREEN_WIDTH - 80, 44)
                                                  title:@"立即登录"
                                             titleColor:UIColor.whiteColor
                                              titleFont:15
                                           cornerRadius:22
                                        backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                        backgroundImage:nil
                                                  image:nil];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [header addSubview:button];
    [button setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedLoginButton];
    }];
    
    
    STButton * fogetbutton = [[STButton alloc] initWithFrame:CGRectMake(0, button.bottom + 20, 100, 30)
                                                       title:@"忘记密码?"
                                                  titleColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                   titleFont:13
                                                cornerRadius:0
                                             backgroundColor:nil
                                             backgroundImage:nil
                                                       image:nil];
    fogetbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [header addSubview:fogetbutton];
    fogetbutton.right = button.right;
    [fogetbutton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedForgetButton];
    }];
    
    
    STButton * codebutton = [[STButton alloc] initWithFrame:CGRectMake(0, button.bottom+20, 100, 30)
                                                       title:@"验证码登录>>"
                                                  titleColor:STONEOBS_UI_SECEND_TEXT_COLOR
                                                   titleFont:13
                                                cornerRadius:0
                                             backgroundColor:nil
                                             backgroundImage:nil
                                                       image:nil];
    [header addSubview:codebutton];
    codebutton.left = button.left;
    [codebutton setClicAction:^(UIButton *sender) {
        [weakSelf pushViewController:THCodeLoginViewController.new animated:1];
    }];
    
    
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(60, codebutton.bottom+30, UISCREEN_WIDTH - 120, 0.5)];
    line.backgroundColor = STONEOBS_UI_THIRD_TEXT_COLOR;
//    [header addSubview:line];
   
    STLabel * titleLabel = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)
                                                     text:@"快捷登录"
                                                textColor:STONEOBS_UI_SECEND_TEXT_COLOR
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    
    titleLabel.centerX = UISCREEN_WIDTH/2;
    titleLabel.centerY = line.centerY;
    titleLabel.backgroundColor = UIColor.whiteColor;
//    [header addSubview:titleLabel];
    
    STButton * wechatbutton = [[STButton alloc] initWithFrame:CGRectMake(0, titleLabel.bottom+30, 44, 44)
                                                  title:nil
                                             titleColor:nil
                                              titleFont:0
                                           cornerRadius:22
                                        backgroundColor:nil
                                        backgroundImage:[UIImage imageNamed:@"微信"]
                                                  image:nil];
    wechatbutton.centerX = UISCREEN_WIDTH / 2;
//    [header addSubview:wechatbutton];
    [wechatbutton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedWechatButton];
    }];
    
    if (@available(iOS 13.0, *)) {
//        UIControl * appleControl = [TMAppleLoginManger.manger createSystemLoginButtonWithType:ASAuthorizationAppleIDButtonTypeSignIn style:ASAuthorizationAppleIDButtonStyleWhiteOutline];
//        appleControl.top = wechatbutton.bottom + 20;
//        appleControl.centerX = UISCREEN_WIDTH/2;
////        [header addSubview:appleControl];
//        header.height = appleControl.bottom + 10;
//        [TMAppleLoginManger.manger setHandle:^(NSString * _Nonnull user_id, NSString * _Nonnull identityToken, NSString * _Nonnull errorStirng) {
//
//            if (identityToken.length) {
//
//            }
//
//
//        }];
        header.height = wechatbutton.bottom + 10;
    } else {
        // Fallback on earlier versions
        header.height = wechatbutton.bottom + 10;
    }
    
    self.tableView.tableHeaderView = header;
    
    self.accountTextFiled.text = [STTools_UserManger.defult account];
    self.pwdTextFiled.text = [STTools_UserManger.defult pwd];
    #ifdef DEBUG
        self.accountTextFiled.text =  @"18181366398";
    #endif
}
- (UITextField*)textFiledWithLeftImage:(NSString*)imageName placeHolader:(NSString*)placeHolader{
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 24, 40)
                                                              title:nil
                                                         titleColor:nil
                                                          titleFont:0
                                                       cornerRadius:0
                                                    backgroundColor:nil
                                                    backgroundImage:nil
                                                              image:ST_IMAGE_NAMED(imageName)];
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(36, 0, UISCREEN_WIDTH - 0 - 36*2, 40)];
    [textFiled stoneobs_fun_setstoneobs_fun_st_leftView:stoneobs_ui_button];
    textFiled.leftViewMode = UITextFieldViewModeAlways;
    textFiled.placeholder = placeHolader;
    textFiled.backgroundColor = UIColor.whiteColor;
    textFiled.rightViewMode = UITextFieldViewModeAlways;
    textFiled.keyboardType = UIKeyboardTypeASCIICapable;
    [textFiled stoneobs_fun_st_showBottomLine];
    return textFiled;
}
#pragma mark --Action Method

- (void)onSelctedForgetButton{
    [self pushViewController:THForgotPwdViewController.new animated:1];
}
- (void)onSelctedWechatButton{
//    [TMWechatSocietyManger.manger beginLoginWithLoginHandle:^(BOOL success, NSString *alert) {
//        if (success) {
//            [TMWechatSocietyManger.manger fetchUserInfoWithHandle:^(NSDictionary *infoDic, NSString *errorDesc) {
//                if (infoDic.allKeys.count) {
//                    NSString * nickname = [infoDic[@"nickname"] description];
//                    NSString * headimgurl = [infoDic[@"headimgurl"] description];
//                    NSArray * array = [headimgurl componentsSeparatedByString:@"/"];
//                    headimgurl =  [headimgurl stringByReplacingOccurrencesOfString:array.lastObject withString:@"0"];
//                    NSString * sex = [infoDic[@"sex"] description];
////                    NSString * openid = [infoDic[@"unionid"] description];
//                    NSString * openid = [infoDic[@"openid"] description];
//                    NSString * unionid = [infoDic[@"unionid"] description];
//                    NSString * city = [infoDic[@"city"] description];
//
//
//                }
//            }];
//        }
//    }];

    
}
- (void)onSelctedLoginButton{
    if (!self.accountTextFiled.text.length) {
        [SVProgressHUD showInfoWithStatus:@"请输入账号"];
        return;
    }
    if (!self.pwdTextFiled.text.length) {
        [SVProgressHUD showInfoWithStatus:@"请输入密码"];
        return;
    }
    [self sendLoginRequest];
}
- (void)gotoTabbar{
    NSArray * array= self.rt_navigationController.rt_viewControllers;
    if ( array.count > 1) {
        NSInteger count = 0;
        for (UIViewController * vc in array) {
            if ([vc isKindOfClass:self.class]) {
                count ++;
            }
        }
        if (count > 1) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
           [self.navigationController popViewControllerAnimated:YES];
        }
        
    }else{
        UIWindow * window =  UIApplication.sharedApplication.delegate.window ;
        window.rootViewController = STTools_TabbarViewController.new;
        [window stoneobs_fun_st_showAnimationWithType:STAnimationTypeCurlUp_stoneobs_enum];
    }

}
#pragma mark --NetWork Method
- (void)sendLoginRequest{
    [SVProgressHUD showWithStatus:@"正在登录"];
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.accountTextFiled.text.length) {
        [stoneobs_net_param_dic setObject:self.accountTextFiled.text forKey:@"phone"];
    }
    if (self.pwdTextFiled.text.length) {
        [stoneobs_net_param_dic setObject:self.pwdTextFiled.text forKey:@"password"];
    }
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/auth/login"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        THUserModel * user = [THUserModel mj_objectWithKeyValues:stoneobs_net_model_dic];
        [STTools_UserManger.defult stoneobs_fun_updateUserModel:user];
        [self gotoTabbar];
        
        [STTools_LocationManger.defult stoneobs_fun_st_startUpdatingLocationHande:^(STTools_Error *error, CLPlacemark *placemark) {
            [STTools_LocationManger.defult stoneobs_fun_st_updatePlacemarkWith:placemark];
            [THUserDataController updatePlace:STTools_LocationManger.defult.latitude lng:STTools_LocationManger.defult.longitude handle:^(NSError *error, BOOL success, NSDictionary *resp) {
                
            }];
        }];
        
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
    
}
@end





